const app = getApp()
import util from '../../../utils/util'
import {
  onMarketGoods
} from '../../../config/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    model: 1,
    phone:'',//手机号码
    content:'',//提交的内容
    imgs: [],
    count: 0,
    compressImgsSizeArr: [],
    member:null,//缓存中的member信息，判断是不是村民
  },


   // 上传图片
   chooseImg: function (e) {
    //console.log('选择图片e', e)
    var that = this;
    var imgs = this.data.imgs;
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 800,
                maxHeight = 600;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                compressImgsSizeArr = that.data.compressImgsSizeArr;
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function () {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    width: targetWidth,
                    height: targetHeight,
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.4,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/UploadsApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data.imgs.push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              imgs: that.data.imgs
                            })
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 1000)
              );

            }
          })

          let count = ++that.data.count;
          console.log('++count', count)
          that.setData({
            count: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },


   // 删除图片
   deleteImg: function (e) {
    var imgs = this.data.imgs;
    var compressImgsSizeArr = this.data.compressImgsSizeArr;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      imgs: imgs,
      compressImgsSizeArr: compressImgsSizeArr
    })
  },

  // 预览图片
  previewImg: function (e) {
    let that = this;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data.imgs;

    console.log('预览时imgs', imgs)
    console.log(imgs[index])
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  //获得手机号
  getPhone(e){
    let that = this;
    console.log('获得的相应的手机号：',e.detail.value);
    that.setData({
      phone:e.detail.value
    });
  },

  //获得输入框的内容
  getContent(e){
    let that = this;
    console.log('获得的相应的内容：',e.detail.value);
    that.setData({
      content:e.detail.value
    });
  },

  showModel(info){
    let that = this;
    wx.showModal({
      title:'提示',
      showCancel: false,
      content:info,
    })
  },//弹出框进行二次封装

  //提交相应的表单
  formSubmit(){
    let that = this;
  //提交前对表单进行相应的验证
    if(that.data.phone.length==0 ){
      that.showModel('联系方式不能为空！');
      return;
    }
    let regPhone=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if(!regPhone.test(that.data.phone)){
       that.showModel('请填写正确的联系方式！');
       return;
    }

    if(that.data.content.length==0 && that.data.imgs.length==0){
      that.showModel('请上传文件或者内容！');
      return;
    }
    //提交前对表单进行相应的验证
    let params = {
      user_name:that.data.member.name,
      vollege_id:app.globalData.vollege_id,
      content:that.data.content.replace(/(^\s*)|(\s*$)/g, ""),
      phone:that.data.phone,
      img_cont:that.data.imgs,
      town_id:app.globalData.town_id,
      idcard:that.data.member.idcard,
      headimg:that.data.member.heard_img?that.data.member.heard_img:'',
      address:''
    };
    util.apiRequest(onMarketGoods,params).then(r=>{
            console.log('提交结果为：',r);
            wx.showModal({
              title: '提示',
              content: r.data.info,
              showCancel:false,
              success (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url:'/pages/index/index',
                  })
                }
              }
            })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     let that = this;
    let model = wx.getStorageSync('model')
    if (model) {
      this.setData({
        model
      })
    }
     let member = wx.getStorageSync('member');
     if(member){
        that.setData({
            member:member,
            phone:member.mobile
        })
     }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})